package com.netease.qa.web.controller;

import com.nestease.qa.dao.entity.User;
import com.netease.qa.biz.dto.UserDTO;
import com.netease.qa.biz.service.UserService;
import com.netease.qa.web.utils.ServiceResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author zoudongdong
 * @date 2018/3/7
 */
@Controller
public class UserController {
    private static Logger log = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult userLogin(@RequestBody UserDTO userDTO, HttpServletRequest request) {
        log.info("******userLogin******");
        UserDTO userDTO2 = userService.verifyLogin(userDTO);
        if (userDTO2 == null) {
            return ServiceResult.successMsg("登录失败,请检查用户名和密码!!!");
        }
        HttpSession session = request.getSession();
        session.setAttribute("loginUser", userDTO2);
        return ServiceResult.successMsg("登录成功");
    }

    @RequestMapping(value = "/userRegister", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult userRegister(@RequestBody UserDTO userDTO) {
        log.info("******userRegister******");

        //如果用户名已经存在,注册失败
        boolean verifyResult = userService.verifyUserName(userDTO.getUserName());
        if(!verifyResult){
            return ServiceResult.successMsg("该用户名已经注册了!!!");
        }
        userService.userRegister(userDTO);
        return ServiceResult.successMsg("注册成功");
    }

    @RequestMapping(value = "/userLoginOut", method = RequestMethod.GET)
    public String userLoginOut(HttpServletRequest request) {
        log.info("******userLoginOut******");

        HttpSession session = request.getSession();
        session.setAttribute("loginUser",null);
        return "redirect:/lego/loginIndex";
    }

}
